﻿using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Yoozoo.UI.YGUI;

public class AlphaReverser: MonoBehaviour
{
    public CanvasGroup targetCanvasGroup;
    public CanvasGroup selfCanvasGroup;
    public int overlayTimes = 1;

    private float startAlpha;
    private bool valid = false;
    
    private void Start()
    {
        if (selfCanvasGroup == null)
        {
            Debug.LogError(name + " 使用了AlphaReverser却没有canvasgroup");
            selfCanvasGroup = gameObject.AddComponent<CanvasGroup>();
        }
        startAlpha = selfCanvasGroup.alpha;
        if (targetCanvasGroup == null)
        {
            FindCanvasGroup();
        }
        selfCanvasGroup.ignoreParentGroups = true;
        valid = targetCanvasGroup != null;
    }
    
    private void LateUpdate()
    {
        if (targetCanvasGroup == null)
        {
            FindCanvasGroup();
        }
        if (!valid)
        {
            return;
        }
        selfCanvasGroup.alpha = Mathf.Pow(targetCanvasGroup.alpha,1f / overlayTimes);
        /*var targetAlpha = targetCanvasGroup.alpha;
        int count = 0;
        var currentAlpha = 1f;
        while (count < overlayTimes)
        {
            currentAlpha = calculateAlpha(targetAlpha, currentAlpha);
            count++;
        }
        selfCanvasGroup.alpha = currentAlpha;*/
    }

    private float calculateAlpha(float target,float a)
    {
        var up = Mathf.Pow(target, 2.2f) - Mathf.Pow(a, 2.2f);
        var down = 1 - a;
        return Mathf.Pow(up / down, 1f / 2.2f);
    }
    
    private void FindCanvasGroup()
    {
        int limit = 5;
        int count = 0;
        var parent = transform.parent;
        while (parent != null)
        {
            var canvasGroup = parent.GetComponent<CanvasGroup>();
            if (canvasGroup)
            {
                targetCanvasGroup = canvasGroup;
                break;
            }
            parent = parent.parent;
            count = count + 1;
            if (count > limit)
            {
                break;
            }
        }
    }

}
